const express = require('express');
const router = express.Router();
const { pool } = require('../db/connection');
const monitoringService = require('../services/monitoringService');
const speedTest = require('speedtest-net');

// 获取当前网络状态数据
router.get('/current-status', async (req, res) => {
  try {
    let networkData;
    let isRealData = false;
    
    try {
      // 使用speedtest-net进行真实网络速度测试，设置超时
      console.log('开始当前网络状态测试...');
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('网络测试超时')), 30000)
      );
      
      const result = await Promise.race([
        speedTest({ acceptLicense: true, acceptGdpr: true }),
        timeoutPromise
      ]);
      
      // 处理网络数据
      networkData = {
        timestamp: new Date().toISOString(),
        ping_ms: Math.round(result.ping.latency),
        download_speed: result.download.bandwidth / 125000, // 转换为Mbps
        upload_speed: result.upload.bandwidth / 125000, // 转换为Mbps
        packet_loss: result.packetLoss || 0,
        bandwidth_usage: Math.round((result.download.bandwidth + result.upload.bandwidth) / 125000),
        connection_status: monitoringService.getConnectionStatus(result.ping.latency, result.download.bandwidth, result.packetLoss)
      };
      
      isRealData = true;
      console.log('真实网络测试成功完成');
      
    } catch (speedTestError) {
      console.log(`网络测试失败或超时: ${speedTestError.message}，使用模拟数据`);
      // 测试失败时使用模拟数据作为备选
      const randomFactor = Math.random();
      networkData = {
        timestamp: new Date().toISOString(),
        ping_ms: Math.floor(Math.random() * 100) + 10,
        download_speed: Math.random() * 100,
        upload_speed: Math.random() * 50,
        packet_loss: Math.random() * 5,
        bandwidth_usage: Math.random() * 100,
        connection_status: randomFactor > 0.95 ? 'disconnected' : randomFactor > 0.85 ? 'unstable' : 'connected'
      };
    }
    
    // 将数据保存到数据库
    await pool.execute(
      'INSERT INTO network_status (ping_ms, download_speed, upload_speed, packet_loss, bandwidth_usage, connection_status) VALUES (?, ?, ?, ?, ?, ?)',
      [networkData.ping_ms, networkData.download_speed, networkData.upload_speed, networkData.packet_loss, networkData.bandwidth_usage, networkData.connection_status]
    );
    
    // 转换数据格式以匹配前端期望
    const responseData = {
      ping: networkData.ping_ms,
      download_speed: networkData.download_speed,
      upload_speed: networkData.upload_speed,
      status_text: networkData.connection_status === 'connected' ? '正常' : networkData.connection_status === 'unstable' ? '不稳定' : '断开',
      timestamp: networkData.timestamp,
      packet_loss: networkData.packet_loss,
      bandwidth_usage: networkData.bandwidth_usage,
      data_source: isRealData ? 'real' : 'simulated' // 标记数据来源
    };
    
    console.log(`当前网络状态${isRealData ? '(真实数据)' : '(模拟数据)'}: ping=${responseData.ping}ms, download=${responseData.download_speed.toFixed(2)}Mbps, upload=${responseData.upload_speed.toFixed(2)}Mbps`);
    
    res.json({ success: true, data: responseData });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// 获取历史数据分析
router.get('/history', async (req, res) => {
  try {
    const { days = 7 } = req.query;
    const [rows] = await pool.execute(
      `SELECT * FROM network_history 
       WHERE date >= DATE_SUB(NOW(), INTERVAL ? DAY) 
       ORDER BY date DESC`,
      [days]
    );
    res.json({ success: true, data: rows });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// 获取实时监测指标（最近100条记录）
router.get('/realtime-metrics', async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT timestamp, ping_ms, download_speed, upload_speed, packet_loss FROM network_status ORDER BY timestamp DESC LIMIT 100'
    );
    res.json({ success: true, data: rows });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// 警报功能已移除

// 生成模拟历史数据
router.post('/generate-mock-data', async (req, res) => {
  try {
    // 生成过去30天的模拟数据
    for (let i = 30; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const formattedDate = date.toISOString().split('T')[0];
      
      // 检查是否已存在数据
      const [existing] = await pool.execute('SELECT * FROM network_history WHERE date = ?', [formattedDate]);
      if (existing.length === 0) {
        const mockHistoryData = {
          date: formattedDate,
          avg_ping: Math.floor(Math.random() * 50) + 20,
          max_download: Math.random() * 100 + 50,
          max_upload: Math.random() * 50 + 20,
          uptime_percentage: Math.random() * 10 + 90,
          total_traffic: Math.random() * 1000 + 500
        };
        
        await pool.execute(
          'INSERT INTO network_history (date, avg_ping, max_download, max_upload, uptime_percentage, total_traffic) VALUES (?, ?, ?, ?, ?, ?)',
          [mockHistoryData.date, mockHistoryData.avg_ping, mockHistoryData.max_download, mockHistoryData.max_upload, mockHistoryData.uptime_percentage, mockHistoryData.total_traffic]
        );
      }
    }
    
    res.json({ success: true, message: '模拟数据生成成功' });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// 启动实时监控
router.post('/monitoring/start', (req, res) => {
  try {
    const result = monitoringService.startMonitoring();
    if (result.success) {
      res.status(200).json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// 停止实时监控
router.post('/monitoring/stop', (req, res) => {
  try {
    const result = monitoringService.stopMonitoring();
    if (result.success) {
      res.status(200).json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// 获取监控状态
router.get('/monitoring/status', (req, res) => {
  try {
    const status = monitoringService.getStatus();
    res.status(200).json({ success: true, data: status });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

module.exports = router;